package com.suep.system.controller;

import com.suep.system.config.BaseR;
import com.suep.system.domain.User;
import com.suep.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/register")
public class RegisterController {
    @Autowired
    private IUserService userService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @PostMapping
    public BaseR register(@RequestBody Map<String,Object> registerForm){

         String phone=(String) registerForm.get("phone");
        String email=(String)registerForm.get("email");
         String password=(String)registerForm.get("password");
//         String passwordAgain,
//         Boolean allow,
        String verificationCode=(String)registerForm.get("verificationCode");
        String storedCode = redisTemplate.opsForValue().get(email);
        //先核验用户输入的验证码是否正确
        if (storedCode == null) {
            return new BaseR<>().error("验证码已经过期，请重新点击发送！！");
        }
        if (!storedCode.equals(verificationCode)) {
            return new BaseR<>().error("验证码输入错误，请仔细查看验证码");
        }

        User user=new User();
        user.setEmail(email);
        user.setPassword(password);
        user.setNickname("WM用户"+email);
        user.setUsername(phone);
        user.setState(1);
        if(userService.insertUser(user)==1) {
            return new BaseR<>().ok("注册成功");
        }
        return new BaseR<>().error("注册失败");
    }
}
